//
//  GoogleMapShow.m
//  GoogleMapDemo
//
//  Created by Acme on 2/23/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MapViewCtrl.h"
#import "BridgeAnnotation.h"


@implementation MapViewCtrl
@synthesize map,map_lat,map_lng,loc_lat,loc_lng;
@synthesize is_edit;

- (void)dealloc {
    if (pioAnn!=nil) {
		[pioAnn release];
		pioAnn =  nil;
	}
	locmanager.delegate = nil;
	locmanager = nil;
	[map release];
	map = nil;
    [super dealloc];
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

-(void)actMapDone:(id)sender {
	NSUserDefaults *_userdef = [NSUserDefaults standardUserDefaults];
	[_userdef setObject:[NSString stringWithFormat:@"%f,%f",map_lng,map_lat] forKey:@"shopMapPoint"];
    NSLog(@"%f,%f",map_lat,map_lng);
	[self.navigationController popViewControllerAnimated:YES];

//	ShopAddViewCtrl *parentCtrl = [allCtrls lastObject];
//	parentCtrl.map_lat = map_lat;
//	parentCtrl.map_lng = map_lng;	
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
//	viewTouch = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
//	[self.view addSubview:viewTouch];
	[super viewDidLoad];
	UIBarButtonItem *tintButton = [[UIBarButtonItem alloc] initWithTitle:@"标注"
																   style:UIBarButtonItemStyleBordered
																  target:self
																  action:@selector(actMapDone:)];
	self.navigationItem.rightBarButtonItem = tintButton;
	[tintButton release];
//	self.navigationItem.rightBarButtonItem.enabled = YES;
//	self.navigationItem.rightBarButtonItem.title = @"标注";
//	self.navigationItem.rightBarButtonItem.action = @selector(actMapDone);
//	self.navigationItem.rightBarButtonItem.target = self;

	{
		locmanager = [[CLLocationManager alloc] init]; 
		[locmanager setDelegate:self]; 
		[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];	
		[locmanager startUpdatingLocation];
		
		CLLocationCoordinate2D theCenter;

		MKCoordinateRegion theRegin;
		theCenter.latitude =map_lat; 
		theCenter.longitude = map_lng;
		theRegin.center=theCenter;
		
		MKCoordinateSpan theSpan;
		theSpan.latitudeDelta = 0.003;
		theSpan.longitudeDelta = 0.003;
		theRegin.span = theSpan;
		[map setRegion:theRegin];
		[map regionThatFits:theRegin];
		map.delegate = self;
		
	}

	pioAnn = [[BridgeAnnotation alloc]init];
	pioAnn.pio_lat = map_lat;
	pioAnn.pio_lng = map_lng;
	[map addAnnotation:pioAnn];
    
//    UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
//    lpress.minimumPressDuration = 0.3;//按0.5秒响应longPress方法
//    lpress.allowableMovement = 10.0;
//    //给MKMapView加上长按事件
//    [map addGestureRecognizer:lpress];//mapView是MKMapView的实例
//    [lpress release];
	

    
	self.view.userInteractionEnabled = YES;

}

- (IBAction)gotoMyLocation:(id)sender {
	if (loc_lat !=0 || loc_lng!=0) {
		MKCoordinateRegion newRegion;
		newRegion.center.latitude = loc_lat;
		newRegion.center.longitude = loc_lng;
		newRegion.span.latitudeDelta = 0.112872;
		newRegion.span.longitudeDelta = 0.109863;
		
		[map setRegion:newRegion animated:YES];
        
        map_lat = loc_lat;
        map_lng = loc_lng;
        if (pioAnn==NULL) {
            pioAnn = [[BridgeAnnotation alloc]init];
        }
        pioAnn.pio_lat = map_lat;
        pioAnn.pio_lng = map_lng;
        [map removeAnnotation:pioAnn];        
        [map addAnnotation:pioAnn];
		
	}

}


#pragma mark MKMapViewDelegate

//- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
//{}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
	MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
	if (is_edit) {
	map_lat = centerCoordinate.latitude;
	map_lng = centerCoordinate.longitude;
	if (pioAnn==NULL) {
		pioAnn = [[BridgeAnnotation alloc]init];
	}
	pioAnn.pio_lat = map_lat;
	pioAnn.pio_lng = map_lng;
	[map removeAnnotation:pioAnn];        
	[map addAnnotation:pioAnn];
	}
}

//- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView;
//- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView;
//- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error;

// mapView:viewForAnnotation: provides the view for each annotation.
// This method may be called for all or some of the added annotations.
// For MapKit provided annotations (eg. MKUserLocation) return nil to use the MapKit provided annotation view.
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{	
	
//	CGRect rect = CGRectMake(0, 0, 320, 460);
//	map = [[MKMapView alloc] initWithFrame:rect];
	CLLocationCoordinate2D loc = [newLocation coordinate];
	self.loc_lat = loc.latitude;
	self.loc_lng	= loc.longitude;
//	NSLog(@"lat %f",lat);
//	NSLog(@"lon %f",lon);
//	CLLocationCoordinate2D theCoordinate;
//	CLLocationCoordinate2D theCenter;
//	
//	theCoordinate.latitude =lat;
//	theCoordinate.longitude=lon;
//	[map setDelegate: self];
//	//[map setCenter:CGPointMake(160, 240)] ;
//	[map setMapType: MKMapTypeStandard];
//	
//	MKCoordinateRegion theRegin;
//	theCenter.latitude =lat; 
//	theCenter.longitude = lon;
//	theRegin.center=theCenter;
//	
//	MKCoordinateSpan theSpan;
//	theSpan.latitudeDelta = 0.1;
//	theSpan.longitudeDelta = 0.1;
//	theRegin.span = theSpan;
//	[map setRegion:theRegin];
//	[map regionThatFits:theRegin];

	map.showsUserLocation=YES;
	
	//	map.mapType =MKMapTypeHybrid;
	/*
	 MKMapView * aMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
	 self.map = aMapView;
	 [aMapView release];
	 [map setDelegate:self];
	 map.scrollEnabled = YES; 
	 map.zoomEnabled = YES; 
	 [map setShowsUserLocation:YES];
	 map.userLocation.subtitle = @"You are here";
	 */
//	[self.view addSubview:map];
}

/*
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [[event allTouches] anyObject];

	CGPoint touchPoint = [touch  locationInView:viewTouch]; 
	
	        CLLocationCoordinate2D touchMapCoordinate =
	        [map convertPoint:touchPoint toCoordinateFromView:map];
	        
	        map_lat = touchMapCoordinate.latitude;
	        map_lng = touchMapCoordinate.longitude;
	        
	        if (pioAnn==nil) {
	            pioAnn = [[BridgeAnnotation alloc]init];
	        }
	        pioAnn.pio_lat = map_lat;
	        pioAnn.pio_lng = map_lng;
	        [map removeAnnotation:pioAnn];
	        [map addAnnotation:pioAnn];
	
//	[map touchesEnded:touches withEvent:event];

	//	if ([touch view] != UIImageView) {
//		NSLog(@"do something");
//	}
}
 
*/

//- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
//{
//    MKPinAnnotationView *pinView = nil;
//    if(annotation != map.userLocation) 
//    {
//        static NSString *defaultPinID = @"目的地";
//        pinView = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
//        if ( pinView == nil )
//            pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
//        
//        pinView.pinColor = MKPinAnnotationColorPurple;
//        pinView.canShowCallout = YES;
//        pinView.animatesDrop = YES;
////        pinView.draggable=YES;
//        pinView.selected=YES;
//    }
//    else
//    {
//        [map.userLocation setTitle:@"I am here"];
//    }
//    
//    return pinView;
//}

//- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
//{
//	//method one：using default pin as a PlaceMarker to display on map
//	NSLog(@"creatview");
//	MKPinAnnotationView *newAnnotation = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation1"];
//	//newAnnotation.pinColor = MKPinAnnotationColorGreen;
//	newAnnotation.animatesDrop = YES; 
//	//canShowCallout: to display the callout view by touch the pin
//	newAnnotation.canShowCallout=YES;
//	return newAnnotation;
//}

// mapView:didAddAnnotationViews: is called after the annotation views have been added and positioned in the map.
// The delegate can implement this method to animate the adding of the annotations views.
// Use the current positions of the annotation views as the destinations of the animation.
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{	}

// mapView:annotationView:calloutAccessoryControlTapped: is called when the user taps on left & right callout accessory UIControls.
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{	}
#pragma mark CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


//- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
//{
//	MKPinAnnotationView *pinView = nil;
//	
//	static NSString *defaultPinID = @"com.invasivecode.pin";
//	pinView = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
//	if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
//									  initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
//	pinView.pinColor = MKPinAnnotationColorRed;
//	pinView.canShowCallout = YES;
//	pinView.animatesDrop = YES;
//	[map.userLocation setTitle:@"欧陆经典"];
//	[map.userLocation setSubtitle:@"vsp"];
//	return pinView;
//}


@end
